package com.ty.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 田野
 */
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 处理乱码
        request.setCharacterEncoding("utf-8");
        // 防止用户在为登陆的情况下访问资源
        // 获得请求地址
        String requestURI = request.getRequestURI();
        System.out.println("requestURI=" + requestURI);

        boolean flag = requestURI.contains("index.jsp") || requestURI.contains("left.jsp") ||
                requestURI.contains("head.jsp") || requestURI.contains("right.jsp") ||
                requestURI.contains("add.jsp") || requestURI.contains("edit.jsp") ||
                requestURI.contains("list.jsp");
        boolean check = (flag || requestURI.endsWith("/"));

        Object user = request.getSession().getAttribute("u1");
        if ( check && user == null){
            response.sendRedirect("login.jsp");
        }

        // 调取下一个过滤器 或者调取servlet
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }
}
